library(scales)
library(dplyr)
library(tidyr)
library(ggplot2)

# Define region list and label mapping
c_list_agg <- c(
  "East Asia & Pacific (excluding high income)", "Europe & Central Asia (excluding high income)", 
  "Latin America & Caribbean (excluding high income)", "Middle East & North Africa (excluding high income)", 
  "South Asia (excluding high income)", "Sub-Saharan Africa (excluding high income)"
)

legend_labels <- c(
  "East Asia & Pacific (excluding high income)" = "East Asia and Pacific",
  "Europe & Central Asia (excluding high income)" = "Europe and Central Asia",
  "Latin America & Caribbean (excluding high income)" = "Latin America and the Caribbean", 
  "Middle East & North Africa (excluding high income)" = "Middle East and North Africa", 
  "South Asia (excluding high income)" = "South Asia", 
  "Sub-Saharan Africa (excluding high income)" = "Sub-Saharan Africa"
)

# Prepare the data
data_cut <- data %>%
  filter(year %in% c(2021, 2024)) %>%
  filter(group == "all") %>%
  filter(countrynewwb %in% c_list_agg) %>%
  mutate(
    ts_savother = ts_anysavings - ifelse(is.na(ts_savfor_mm), 0, ts_savfor_mm) - ts_savfor_fi_MErank - ts_savsemfor_MErank,
    saved_fi_only = ts_savfor_fi_MErank,
    saved_mm_only = ts_savfor_mm_MErank,
    saved_both = (ts_savfor_mm + ts_savfor_fi - ts_savfor_fi_mm),
    saved_semi_other = ts_savsemfor + ts_savother
  )

plot_sav <- data_cut %>%
  select(countrynewwb, year, saved_fi_only, saved_mm_only, saved_both, saved_semi_other, ts_anysavings) %>%
  pivot_longer(cols = c(saved_fi_only, saved_both, saved_mm_only, saved_semi_other), names_to = "group", values_to = "value") %>%
  mutate(
    total = ts_anysavings * 100,
    value = value * 100
  ) %>%
  filter(!is.na(value)) %>%
  mutate(country_label = recode(countrynewwb, !!!legend_labels))

# Create plot with one-line layout
p <- ggplot(plot_sav) +
  geom_bar(
    aes(
      x = factor(year),
      y = value,
      fill = factor(group, levels = c(
        "saved_semi_other", "saved_mm_only", "saved_both", "saved_fi_only"
      ))
    ),
    stat = "identity",
    position = "stack",
    width = 0.75,
    color = "black",
    size = 0.75
  ) +
  scale_fill_manual(
    values = c(
      "saved_fi_only" = "#5696D0",
      "saved_both" = "#8066AB",
      "saved_mm_only" = "#D12891",
      "saved_semi_other" = "#C2C0C0"
    ),
    breaks = c("saved_fi_only", "saved_both", "saved_mm_only", "saved_semi_other"),
    labels = c(
      "Saved formally at a bank or similar financial institution only",
      "Saved formally at a bank or similar financial institution and using a mobile money account",
      "Saved formally using a mobile money account only",
      "Saved semiformally or using other methods only"
    )
  ) +
  scale_y_continuous(
    limits = c(0, 110),
    breaks = seq(0, 110, by = 20)
  ) +
  facet_grid(. ~ country_label,
             scales = "free_x",
             space = "free_x",
             switch = "both",
             labeller = label_wrap_gen(width = 18)) +
  theme(
    strip.placement = "outside",
    strip.text.x = element_text(size = 16, family = "Nunito Sans", colour = "black", angle = 0),
    panel.background = element_blank(),
    strip.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    legend.title = element_blank(),
    legend.position = "bottom",
    legend.justification = "center",
    legend.box.margin = margin(0, 0, 20, 0),
    axis.text.x = element_text(size = 14, family = "Nunito Sans", color = "black", margin = margin(t = 5)),
    axis.text.y = element_text(size = 14, family = "Nunito Sans", color = "black"),
    axis.ticks.x = element_blank(),
    axis.ticks.y = element_line(color = "black"),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    plot.subtitle = element_text(size = 18, color = "black", family = "Nunito Sans"),
    plot.title = element_text(hjust = 0, size = 22, color = "black", family = "Nunito Sans", face = "bold"),
    plot.title.position = "plot",
    legend.text = element_text(hjust = 0, size = 16, color = "black", family = "Nunito Sans"),
    legend.text.align = 0,
    plot.caption = element_text(size = 18, family = "Nunito Sans", hjust = 0),
    plot.caption.position = "plot",
    plot.margin = margin(t = 10, r = 10, b = 40, l = 10)
  ) +
  guides(fill = guide_legend(ncol = 1)) +
  labs(
    subtitle = "Adults saving any money in the past years (%), 2021-2024",
    title = "Mobile money accounts are an important mode of saving in Sub-Saharan Africa and Latin America and the Caribbean",
    caption = "\n\nSource: Global Findex Database 2025\n\nNote: People may save in multiple ways, but categories in the figure are constructed to be mutually exclusive. 'Saved formally' includes all adults who saved any\nmoney formally. 'Saved semiformally' includes all adults who saved money semiformally but not formally."
  )

# Show plot
p

# Save plot
ggsave(
  filename = file.path(folder_path, "3.1.4.png"),
  plot = p,
  width = 18,
  height = 9,
  units = "in",
  device = 'png',
  dpi = 120
)